<template>
  <div class="app-container">
    <PageTools>
      <template #left>
        <span>总的记录数：{{ total }}条</span>
      </template>
      <template #right>
        <el-button type="warning">导入excel</el-button>
        <el-button type="danger" @click="hExport">导出excel</el-button>
        <el-button type="primary" @click="hAdd">新增员工</el-button>
      </template>
    </PageTools>

    <el-card style="margin-top: 10px;">
      <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template #default="{row}">
            <img :src="row.staffPhoto" alt="" style="width:100%">
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" sortable />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template #default="{row}">
            {{ formatHireType(row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry" sortable />
        <el-table-column label="操作" width="280">
          <template #default="{row}">
            <!-- 方式一：$router.push(`/employees/detail?id=${row.id}`)  查询参数传递参数 -->
            <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
            <!-- 方式二： 路径参数 $router.push(`/employees/detail/${row.id}` -->
            <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button> -->
            <el-button type="text" size="small" @click="hPer(row.id)">分配角色</el-button>
            <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">

        <el-pagination
          :current-page="page"
          :page-sizes="[2, 3, 5, 8, 10]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 新增对话框组件 -->
    <el-dialog
      title="新增员工"
      :visible.sync="dialogFormVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="hClose"
    >
      <addOrEdit ref="myEmp" @success="hSuccess" @close="dialogFormVisible = false" />
    </el-dialog>

    <!-- 分配角色组件 -->
    <el-dialog
      title="分配角色"
      :visible.sync="permissionShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <assginPer :id="isId" ref="assginPer" @close="permissionShow=false" />
    </el-dialog>
  </div>
</template>

<script>
import assginPer from './assignRole.vue'
import addOrEdit from './empDialog.vue'
import { delEmployee, getEmployeeList } from '@/api/employees'
import employeesEnum from '@/constant/employees'

const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addOrEdit,
    assginPer
  },
  data() {
    return {
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示的条数
      total: 0,
      dialogFormVisible: false,
      permissionShow: false,
      isId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 格式化excel的数据格式
    formatData(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'enableState': '未知',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]

      // 1 生成表头
      const one = list[0] // unfined || 有数据
      if (!one) return
      //  Object.keys(one)---> ['correctionTime','id','password','mobile']
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      // 2 生成表的内容data
      const data = list.map(item => {
        return Object.values(item)
      })

      return { tHeader, data }
    },
    // 聘用形式
    formatHireType(value) {
      return hireType[value] || '未定'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 页面加载
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.data.rows
        this.total = res.data.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 添加
    hAdd() {
      this.dialogFormVisible = true
    },
    // 分配角色
    hPer(id) {
      this.isId = id
      this.permissionShow = true
      this.$nextTick(() => {
        this.$refs.assginPer.loadPermissionList()
      })
    },
    // 删除
    hDel(id) {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        if (this.list.length === 1) {
          this.page--
        } if (this.page <= 0) {
          this.page = 1
        }
        const res = await delEmployee(id)
        if (res.data.code === 10000) {
          this.loadEmployeeList()
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 成功后关闭弹窗并渲染
    hSuccess() {
      // 将当前的页码值切换到最后一页
      // if(this.isEdit)
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.dialogFormVisible = false
      this.loadEmployeeList()
    },
    // 重置表单
    hClose() {
      this.$refs.myEmp.resetForm()
    },
    hExport() {
      const { tHeader, data } = this.formatData(this.list)
      // excel表示导入的模块对象
      console.log(tHeader, data)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({ // 将格式化的数据写入excel
          header: tHeader,
          data,
          filename: '', // 设置文件的名称 ''
          autoWidth: true, // 宽度自适应 true
          bookType: 'xlsx' // 导入的文件类型 'xlsx'
        })
      })
    }
  }
}
</script>

<style>
</style>
